/**
 * Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */
package com.mbfasttrack.controller;

import com.mbfasttrack.model.Group;
import com.mbfasttrack.model.Like;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author Marco Berri marcoberri@gmail.com http://tecnicume.blogspot.com
 */
@Controller
public class GroupController extends Base {

    /**
     *
     * @param group
     * @param model
     * @return
     */
    @RequestMapping(value = "/group/save", method = RequestMethod.POST)
    public String save(@ModelAttribute("group") Group group, Model model) {
        if (isGuest()) {
            return "redirect:/login";
        }
        org.springframework.security.core.userdetails.User u = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        group = groupService.add(group, u.getUsername());

        try {
            actionService.add(u.getUsername(), group);
        } catch (Exception e) {
            System.err.println("Problemi nel salvataggio della group:" + e.getMessage());
            log.fatal(e);
            //in caso di non scaricamento devo segnare la track e farlo successivamente in cron
        }
        return "redirect:/group/details/" + group.getSlug();
    }

    /**
     *
     * @param slug
     * @param group
     * @param model
     * @return
     */
    @RequestMapping(value = "/group/modify/{slug}/save", method = RequestMethod.POST)
    public String processSubmitModify(@PathVariable String slug, @ModelAttribute("group") Group group, Model model) {
        Group group_loaded = groupService.groupRepository.findOneBySlug(group);
        group_loaded.setActivity(group.getActivity());
        group_loaded.setName(group.getName());
        group_loaded.setDescription(group.getDescription());
        group = groupService.save(group_loaded);
        model.addAttribute("group", group);
        return "group/add";
    }

    /**
     * Dettaglio del gruppo
     *
     * @param slug
     * @param model
     * @return
     */
    @RequestMapping(value = "/group/like/{slug}", method = RequestMethod.GET)
    public String addLike(@PathVariable String slug, Model model) {
        if (isGuest()) {
            return "redirect:/login";
        }
        Group group = groupService.groupRepository.findOneBySlug(slug);
        org.springframework.security.core.userdetails.User u = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Like l = likeService.add(group, u.getUsername(), Boolean.TRUE);
        actionService.add(u.getUsername(), l, group);
        return "response/ok";
    }

    /**
     *
     * @param slug
     * @param username
     * @param model
     * @return
     */
    @RequestMapping(value = "/group/adduser/{slug}/{username}", method = RequestMethod.GET)
    public String addUser(@PathVariable String slug, @PathVariable String username, Model model) {
        if (isGuest()) {
            return "redirect:/login";
        }
        Group group = groupService.groupRepository.findOneBySlug(slug);
        org.springframework.security.core.userdetails.User u = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!group.getUser().getUsername().equals(u.getUsername())) {
            return "response/ko";
        }

        groupService.addUser(group, username);
        return "response/ok";
    }

    /**
     *
     * @param slug
     * @param trackslug
     * @param model
     * @return
     */
    @RequestMapping(value = "/group/addtrack/{slug}/{trackslug}", method = RequestMethod.GET)
    public String addTrack(@PathVariable String slug, @PathVariable String trackslug, Model model) {
        Group group = groupService.addTrack(slug, trackslug);
        if (group != null) {
            // actionService.add(group, trackslug, "addtracktogroup",);
            return "response/ok";
        } else {
            return "response/ko";
        }
    }

    /**
     *
     * @param slug
     * @param username
     * @param model
     * @return
     */
    @RequestMapping(value = "/group/adduseradmin/{slug}/{username}", method = RequestMethod.GET)
    public String addUserAdmin(@PathVariable String slug, @PathVariable String username, Model model) {
        if (isGuest()) {
            return "redirect:/login";
        }
        Group group = groupService.groupRepository.findOneBySlug(slug);
        org.springframework.security.core.userdetails.User u = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!group.getUser().getUsername().equals(u.getUsername())) {
            return "response/ko";
        }
        groupService.addUserAdmin(group, username);
        return "response/ok";
    }

    /**
     *
     * @param iDisplayLength
     * @param response
     * @param iDisplayStart
     */
    @RequestMapping(value = "/group/json/all", method = RequestMethod.GET)
    public void jsonSearch(@RequestParam(value = "iDisplayLength", required = false) Integer iDisplayLength, @RequestParam(value = "iDisplayStart", required = false) Integer iDisplayStart, HttpServletResponse response) {
        try {

            int page = 0;
            if (iDisplayStart != null && iDisplayStart != 0) {
                page = iDisplayStart / iDisplayLength;
            }

            Page<Group> groups = groupService.groupRepository.findAll(new PageRequest(page, iDisplayLength, Sort.Direction.DESC, "dateSaved"));

            if (groups == null) {
                return;
            }

            ObjectMapper mapper = new ObjectMapper();


            HashMap result = new HashMap();
            result.put("iTotalRecords", groups.getTotalElements());
            result.put("iTotalDisplayRecords", groups.getTotalElements());


            org.springframework.security.core.userdetails.User u = null;
            try {
                u = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            } catch (Exception e) {
                log.fatal(e);
            }

            ArrayList aaData = new ArrayList();
            for (Group g : groups.getContent()) {
                ArrayList dati = new ArrayList();
                dati.add("<a style=\"padding-left:2px\" href=\"" + sys_site_url + "group/details/" + g.getSlug() + "\">" + g.getName() + "</a>");
                dati.add(g.getActivity());
                dati.add(g.getUserLink().size());
                dati.add("<a href=\"" + sys_site_url + "user/details/" + g.getUser().getUsername() + "\">" + g.getUser().getUsername() + "</a>");
                aaData.add(dati);

            }

            result.put("aaData", aaData);

            String jsonString = mapper.writeValueAsString(result);

            AbstractHttpMessageConverter<String> stringHttpMessageConverter = new StringHttpMessageConverter();

            MediaType jsonMimeType = MediaType.APPLICATION_JSON;

            if (stringHttpMessageConverter.canWrite(String.class, jsonMimeType)) {

                try {

                    stringHttpMessageConverter.write(jsonString, jsonMimeType, new ServletServerHttpResponse(response));

                } catch (Exception e) {
                    System.err.println(e.getMessage());
                    log.fatal(e);
                }

            }

        } catch (Exception e) {
            System.err.println(e.getMessage());
            log.fatal(e);

        }

    }

    /**
     *
     * @param type
     * @param slug
     * @param model
     * @return
     */
    @RequestMapping(value = "/group/{type}/{slug}", method = RequestMethod.GET)
    public String getDetails(@PathVariable String type, @PathVariable String slug, Model model) {
        model = this.getBaseModel(model);
        Group group = groupService.groupRepository.findOneBySlug(slug);
        model.addAttribute("group", group);
        if (commentService.findAllByObjectId(group.getId()) != null) {
            model.addAttribute("comments", commentService.findAllByObjectId(group.getId()));
        }
        return "group/" + type;
    }
}